package hk.m4s.lr.repair.test.ui.baoyang;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import framework.common.Constant;
import framework.common.alertview.AlertView;
import framework.common.alertview.OnItemClickListener;
import framework.common.baseui.UeBaseActivity;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.LatModel;
import hk.m4s.lr.repair.test.model.MainInfoModel;
import hk.m4s.lr.repair.test.model.MaintenanceInfoModel;
import hk.m4s.lr.repair.test.model.MaintenanceInfoModelResult;
import hk.m4s.lr.repair.test.model.MaintenanceModelResult;
import hk.m4s.lr.repair.test.model.MaintenanceModle;
import hk.m4s.lr.repair.test.service.device.DeviceListervice;
import hk.m4s.lr.repair.test.ui.adapter.DeviceMainListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.DeviceSelectListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.DeviceShopListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.DeviceShowListAdapter;
import hk.m4s.lr.repair.test.ui.equipment.DeviceReplayActivity;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import hk.m4s.lr.repair.test.views.listview.InnerListView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/23.
 * 设备保养
 */

public class DeviceMainTainActivity extends UeBaseActivity implements View.OnClickListener, OnItemClickListener {
    private RelativeLayout click_fanwei, click_shop, select_la, click_allShop;
    private LinearLayout showAncy, show_img, show_content, select_ly;
    private TextView fabu_fanwei, user_shop, home_send_order, brandS, allS,ancyTips;
    private InnerListView device_list;
    private ListView select_order, de_list, info_list;
    private TabLayout mTabLayout;
    private Button btn_canle, btn_confirm;
    private DeviceMainListAdapter deviceMainListAdapter;
    private DeviceSelectListAdapter deviceSelectListAdapter;
    private DeviceShopListAdapter shopListAdapter;
    private DeviceShowListAdapter deviceShowListAdapter;
    private Context context;
    private List<MaintenanceModle> list = new ArrayList<>();
    private List<MainInfoModel.ListBean> lists = new ArrayList<>();
    List<LatModel> latModelList = new ArrayList<>();
    private String id = "", shopName = "", fabuName = "", agencyId = "", pushArea = "";
    private View view;
    PopupWindow popupWindow;
    private int state = 1;
    private int type = 1;
    int select=1;
    String phone;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_main_tain);
        context = this;
        hiddenFooter();
        showGoBackBtn();
        setTitleText("设备保养");
        findBaseView();
    }

    public void findBaseView() {
        device_list = (InnerListView) findViewById(R.id.select_device);
        click_fanwei = (RelativeLayout) findViewById(R.id.click_fanwei);
        click_shop = (RelativeLayout) findViewById(R.id.click_shop);
        select_la = (RelativeLayout) findViewById(R.id.select_la);
        click_allShop = (RelativeLayout) findViewById(R.id.click_allShop);
        showAncy= (LinearLayout) findViewById(R.id.showAncy);
        ancyTips= (TextView) findViewById(R.id.ancyTips);
        select_ly = (LinearLayout) findViewById(R.id.select_ly);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);
        show_content = (LinearLayout) findViewById(R.id.show_content);
        fabu_fanwei = (TextView) findViewById(R.id.fabu_fanwei);
        user_shop = (TextView) findViewById(R.id.user_shop);
        brandS = (TextView) findViewById(R.id.brandS);
        allS = (TextView) findViewById(R.id.allS);
        de_list = (ListView) findViewById(R.id.de_list);
        info_list = (ListView) findViewById(R.id.info_list);
        home_send_order = (TextView) findViewById(R.id.home_send_order);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        btn_canle = (Button) findViewById(R.id.btn_canle);
        brandS.setOnClickListener(this);
        allS.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
        btn_canle.setOnClickListener(this);
        home_send_order.setOnClickListener(this);
        click_fanwei.setOnClickListener(this);
        click_shop.setOnClickListener(this);

        deviceSelectListAdapter = new DeviceSelectListAdapter(context, list);
        de_list.setAdapter(deviceSelectListAdapter);
        shopListAdapter = new DeviceShopListAdapter(context, lists);
        info_list.setAdapter(shopListAdapter);
        deviceShowListAdapter = new DeviceShowListAdapter(context, lists);
        device_list.setAdapter(deviceShowListAdapter);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.addTab(mTabLayout.newTab().setText("指定商家"), true);
        mTabLayout.addTab(mTabLayout.newTab().setText("所有商家"));
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    type = 1;
                    click_shop.setVisibility(View.VISIBLE);
                    click_allShop.setVisibility(View.GONE);
                    showAncy.setVisibility(View.GONE);
                } else {
                    type = 2;
                    click_shop.setVisibility(View.GONE);
                    click_allShop.setVisibility(View.VISIBLE);
                    showAncy.setVisibility(View.VISIBLE);
                }
                if(!id.equals("")){
                    deviceMaintenanceInfos(id);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        deviceMaintenanceList();
        de_list.setOnItemClickListener(clickItem);
        info_list.setOnItemClickListener(clickItems);

        device_list.setOnItemClickListener(clickItemss);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_fanwei:
                select = 0;
                shopName = "";
                select_la.setVisibility(View.VISIBLE);
                de_list.setVisibility(View.VISIBLE);
                info_list.setVisibility(View.GONE);
                break;
            case R.id.brandS:
                state = 1;
                Drawable drawable = getResources().getDrawable(R.mipmap.checked_hover);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                brandS.setCompoundDrawables(drawable, null, null, null);
                Drawable drawables = getResources().getDrawable(R.mipmap.check);
                drawables.setBounds(0, 0, drawables.getMinimumWidth(), drawables.getMinimumHeight());
                allS.setCompoundDrawables(drawables, null, null, null);
                if (id.equals("")) {
                    ToastUtil.toast(context, "请选择保养单");
                }else {
                    deviceMaintenanceInfos(id);
                }
                break;
            case R.id.allS:
                state = 2;
                Drawable dra = getResources().getDrawable(R.mipmap.checked_hover);
                dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
                allS.setCompoundDrawables(dra, null, null, null);
                Drawable drs = getResources().getDrawable(R.mipmap.check);
                drs.setBounds(0, 0, drs.getMinimumWidth(), drs.getMinimumHeight());
                brandS.setCompoundDrawables(drs, null, null, null);
                if (id.equals("")) {
                    ToastUtil.toast(context, "请选择保养单");
                }else {
                    deviceMaintenanceInfos(id);
                }
                break;
            case R.id.click_shop:
                select = 1;
                de_list.setVisibility(View.GONE);
                info_list.setVisibility(View.VISIBLE);

                if (id.equals("")) {
                    ToastUtil.toast(context, "请选择保养单");
                } else {
                    select_la.setVisibility(View.VISIBLE);
                    deviceMaintenanceInfo(id);
                }
                break;
            case R.id.btn_canle:
                if (select == 0) {
                    fabuName = "";
                    select_la.setVisibility(View.GONE);
                    fabu_fanwei.setText("请选择保养单");
                } else {
                    shopName = "";
                    select_la.setVisibility(View.GONE);
                    user_shop.setText("请选择指定服务商户");
                }
                break;
            case R.id.btn_confirm:
                if (select == 0) {
                    select_la.setVisibility(View.GONE);
                    fabu_fanwei.setText(fabuName);
                } else {
                    select_la.setVisibility(View.GONE);
                    user_shop.setText(shopName);
                }
                break;
            case R.id.home_send_order:
                if (id.equals("")) {
                    ToastUtil.toast(context, "请选择保养单");
                    return;
                }
                if (type == 1) {
                    if (agencyId.equals("")) {
                        ToastUtil.toast(context, "请选择服务商户");
                        return;
                    }
                } else {
                    if (state == 0) {
                        ToastUtil.toast(context, "请选择服务商户");
                        return;
                    }
                }
                select=1;
                new AlertView("提示", "您真的确认将本次保养任务发出去吗?发送成功后,周边服务商会报价给您，您会在通知中收到消息.", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this).setCancelable(true).show();

                break;
        }
    }

    @Override
    public void onItemClick(Object o, int position) {
        //判断是否是拓展窗口View，而且点击的是非取消按钮
        if (position == -1) {
            return;
        } else {
            if (position == 0) {
                if(select==1) {
                    deviceMaintenancePush();
                }else if(select==2){
                    if(!(phone==null||phone.equals(""))){
                        if (ContextCompat.checkSelfPermission(((Activity) context),
                                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // 没有获得授权，申请授权
                            if (ActivityCompat.shouldShowRequestPermissionRationale(((Activity) context),
                                    Manifest.permission.CALL_PHONE)) {
                                // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                                // 弹窗需要解释为何需要该权限，再次请求授权
                                // 帮跳转到该应用的设置界面，让用户手动授权
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                                intent.setData(uri);
                                context.startActivity(intent);
                            } else {
                                // 不需要解释为何需要该权限，直接请求授权
                                ActivityCompat.requestPermissions(((Activity) context),
                                        new String[]{Manifest.permission.CALL_PHONE},
                                        1);
                            }
                        } else {
                            Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" +phone));
                            context.startActivity(phoneIntent);
                        }
                    }else{
                        ToastUtil.toast(context,"电话不正确");
                    }
                }
            }
        }
    }

    public void deviceMaintenanceList() {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            parmas.put("jsonText", jsondata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceListervice.deviceMaintenanceList(context, parmas, new ResponseCallback<MaintenanceModelResult>() {
            @Override
            public void onSuccess(MaintenanceModelResult accountModel) {
                list.clear();
                if (accountModel.getList() != null) {
                    list.addAll(accountModel.getList());
                    deviceSelectListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    public void deviceMaintenanceInfo(final String id) {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("id", id);
            jsondata.put("type", type);
            jsondata.put("lat",SharedPreferencesUtils.getSharedPreferences(Constant.Latitude,""));
            jsondata.put("lng",SharedPreferencesUtils.getSharedPreferences(Constant.Longitude,""));
            parmas.put("jsonText", jsondata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceListervice.deviceMaintenanceInfo(context, parmas, new ResponseCallback<MainInfoModel>() {
            @Override
            public void onSuccess(MainInfoModel accountModel) {
                lists.clear();
                if (accountModel.getList() != null) {
                    show_content.setVisibility(View.VISIBLE);
                    home_send_order.setVisibility(View.VISIBLE);
                    lists.addAll(accountModel.getList());
                    shopListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    public void deviceMaintenanceInfos(final String id) {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("id", id);
            jsondata.put("type", type);
            if(type==2) {
                jsondata.put("supplierType", state);
            }else{
                jsondata.put("supplierType", "");
            }
            jsondata.put("lat",SharedPreferencesUtils.getSharedPreferences(Constant.Latitude,""));
            jsondata.put("lng",SharedPreferencesUtils.getSharedPreferences(Constant.Longitude,""));
            parmas.put("jsonText", jsondata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceListervice.deviceMaintenanceInfo(context, parmas, new ResponseCallback<MainInfoModel>() {
            @Override
            public void onSuccess(MainInfoModel accountModel) {
                lists.clear();
                if (accountModel.getList() != null) {
                    if(accountModel.getList().size()>0) {
                        ancyTips.setVisibility(View.GONE);
                    }else{
                        ancyTips.setVisibility(View.VISIBLE);
                    }
                    show_content.setVisibility(View.VISIBLE);
                    home_send_order.setVisibility(View.VISIBLE);
                    lists.addAll(accountModel.getList());
                }else{
                    ancyTips.setVisibility(View.VISIBLE);
                }
                deviceShowListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    AdapterView.OnItemClickListener clickItem = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            MaintenanceModle deviceModel = list.get(arg2);
            deviceSelectListAdapter.flag = arg2;
            deviceSelectListAdapter.notifyDataSetChanged();
            if (select == 0) {
                fabuName = deviceModel.getMaintenanceOrder();
                id = deviceModel.getId();
                deviceMaintenanceInfos(id);
            }


        }

    };
    AdapterView.OnItemClickListener clickItems = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            MainInfoModel.ListBean deviceModel = lists.get(arg2);

            shopName = deviceModel.getName();
            agencyId = String.valueOf(deviceModel.getSupplierId());
            shopListAdapter.flag = arg2;
            shopListAdapter.notifyDataSetChanged();
        }

    };
    AdapterView.OnItemClickListener clickItemss = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            MainInfoModel.ListBean deviceModel = lists.get(arg2);
            phone=deviceModel.getPhone();
            select=2;
            new AlertView("提示", "是否要拨打电话", "取消", new String[]{"确定"}, null, DeviceMainTainActivity.this, AlertView.Style.Alert, DeviceMainTainActivity.this).setCancelable(true).show();
        }

    };

    private void showWindow(View parent) {

        if (popupWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            view = layoutInflater.inflate(R.layout.slect_layout, null);

            select_order = (ListView) view.findViewById(R.id.select_order);
            // 创建一个PopuWidow对象
            popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, 350);
        }

        select_order.setAdapter(deviceSelectListAdapter);
        select_order.setOnItemClickListener(clickItem);
        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);

        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        int xPos = windowManager.getDefaultDisplay().getWidth() / 2
                - popupWindow.getWidth() / 2;
        Log.i("coder", "xPos:" + xPos);

        popupWindow.showAsDropDown(parent, xPos, 0);

        select_order.setOnItemClickListener(clickItem);
    }

    public void deviceMaintenancePush() {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("id", id);
            if (type == 1) {
                if (!agencyId.equals("")) {
                    jsondata.put("supplierId", new JSONArray().put(agencyId));
                }
            } else {
                JSONArray array = new JSONArray();
                for (MainInfoModel.ListBean bean : lists) {
                    array.put(bean.getSupplierId());
                }
                jsondata.put("supplierId", array.toString());
            }
            parmas.put("jsonText", jsondata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceListervice.deviceMaintenancePush(context, parmas, new ResponseCallback<MaintenanceInfoModelResult>() {
            @Override
            public void onSuccess(MaintenanceInfoModelResult accountModel) {
                ToastUtil.toast(context,"操作成功");
                finish();
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }
}
